package com.book.servlet.page;

import com.book.entity.Book;
import com.book.entity.Borrow;
import com.book.entity.Student;
import com.book.entity.User;
import com.book.service.BookService;
import com.book.service.StudentService;
import com.book.service.impl.BookServiceImpl;
import com.book.service.impl.StudentServiceImpl;
import com.book.util.ThymeleafUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.thymeleaf.context.Context;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
 **@Author:youpeng
 **Created on 2022/4/24
 */
@WebServlet("/index")
public class IndexServlet extends HttpServlet {

    BookService bookService=new BookServiceImpl();
    StudentService studentService=new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        User user = (User) req.getSession().getAttribute("user");
        context.setVariable("nickname",user.getNickname());
        context.setVariable("numBorrow",bookService.getBorrowList().size());
        context.setVariable("numBook",bookService.getBookList().size());
        context.setVariable("numStudent",studentService.getStudentList().size());
        Map<Book, Boolean> bookList = bookService.getBookList();
        double numPrice= bookList.keySet().stream().mapToDouble(Book::getPrice).sum();
        context.setVariable("numPrice",numPrice);
        String msg = req.getParameter("msg");
        String pageNum = req.getParameter("page");
        int num=pageNum==null?1:Integer.parseInt(pageNum);
        Page<Borrow> page = PageHelper.startPage(num, 5);
        List<Borrow> borrowListLike = bookService.getBorrowListLike(msg == null ? "" : msg);
        context.setVariable("borrowList",borrowListLike);
        PageInfo<Borrow> pageInfo = new PageInfo<>(borrowListLike, 5);
        context.setVariable("pageInfo",pageInfo);
        ThymeleafUtil.process("index.html",context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = req.getParameter("msg");
        req.getSession().setAttribute("msg",msg);
        this.doGet(req,resp);
    }
}
